package com.leyou.cart.interceptor;

import com.leyou.cart.config.JwtProperties;
import com.leyou.common.pojo.UserInfo;
import com.leyou.common.utils.CookieUtils;
import com.leyou.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @create: 2019-07-20 05:12
 **/
@Component
@EnableConfigurationProperties(value = JwtProperties.class)
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtProperties jwtProperties;

    //用来传输获取的用户信息的作用域，使用这个域只会在当前线程内起作用。可以与多线程很好的使用
    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取cookie中的token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());

        //2.解析token，获取用户
        UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());

        //判断用户是否存在
        if (userInfo == null) {
            //拦截
            return false;
        }

        //把userinfo放入线程局部变量内
        THREAD_LOCAL.set(userInfo);
        //放行
        return true;
    }

    /**
     * 给外部用来直接获取userinfo的方法
     *
     * @return
     */
    public static UserInfo getUserInfo() {
        return THREAD_LOCAL.get();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //在监听的方法完成之后，调用监听类的完成方法，清空我们的线程局部变量。释放资源。
        // 因为我们使用的是tomcat的线程池，线程不会结束，就不会自动释放资源
        //这一步很重要
        THREAD_LOCAL.remove();
    }
}
